package com.controller;

import com.mysql.cj.Session;
import com.pojo.User;
import com.pojo.Worker;
import com.service.UserService;
import com.service.WorkerService;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private WorkerService workerService;

    @Autowired
    private UserService userService;

    @RequestMapping("/loginValidate")
    public String aaa(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("identity") String identity, Model model, HttpServletResponse response, HttpSession session) throws IOException {
        User user = null;
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();
        if(identity.equals("0")) {
            //如果是管理员
            user = userService.findAdimn(username);
            try {
                session.setAttribute("id", user.getId());
                model.addAttribute("id", user.getId());
            }
            catch (Exception ignored)
            {

            }
        }else{
            try {
                user = userService.findStaff(username);
                int id = user.getId();
                Worker worker = workerService.queryById(id);
                session.setAttribute("id", user.getId());
                model.addAttribute("id", user.getId());
                session.setAttribute("worker",worker);
            }
            catch (Exception ignored)
            {

            }
        }

        //如果是员工
        if(user == null) {
            System.out.println("用户名不存在");
            model.addAttribute("error","用户名不存在");
            out.print("<script language='javascript'>alert('账号或密码错误');window.location.href='../';</script>");
            return null;
        }else{
            if(!user.getPassword().equals(password)){
                System.out.println("密码错误");
                model.addAttribute("error","密码错误");
                out.print("<script language='javascript'>alert('账号或密码错误');window.location.href='../';</script>");
                return null;
            }
        }
        System.out.println(user);

        if(identity.equals("1")) {
            //如果是员工
            return "redirect:/worker/allYonghu";
        }
        //如果是管理员
        return "redirect:/worker/allWorker";
    }

    @RequestMapping("test")
    public String test(){
        return "test";
    }

}
